var nbll = {
    setBtnStatus: function () {
        var row = $('#grid_nbll').datagrid('getSelected');
        if (row) {
            if (row.zt == "ybc") {
                $("#btn_nbll_sh").show();
                $("#btn_nbll_bl").hide();
            } else if (row.zt == "ysp") {
                $("#btn_nbll_sh").hide();
                $("#btn_nbll_bl").show();
            }
        } else {
            $("#btn_nbll_sh").hide();
            $("#btn_nbll_bl").hide();
        }
    },
    showDetail: function (id) {
        nbll.alwayshowDetail(id);
    },
    alwayshowDetail: function (id) {
        $('#layout_nbll').layout('remove', 'center');
        $('#layout_nbll').layout('add', {
            region: 'center',
            split: true,
            href: $.webPath() + '/kcgl/nbll/nbll_detail?lldId=' + id
        });
    }
}

$(function () {
    //初始化加载
    initNbll();
    //根据不同的状态切换查询
    $("#toolbar_nbll input[name='nbll_zt']").change(function () {
        nbll_search();
    });
    //查询按钮触发
    $("#btn_nbll_search").click(function () {
        nbll_search();
    });
    //领料申请按钮触发
    $("#btn_nbll_llsq").click(function () {
        nbll_llsq('内部领料', 'nbll_llsq');
    });
    //审核按钮触发
    $("#btn_nbll_sh").click(function () {
        nbll_sh();
    });
    //办理按钮触发
    $("#btn_nbll_bl").click(function () {
        nbll_bl('发料', 'nbll_bl');
    });
});

//领料申请方法
function nbll_llsq(title, action) {
    var href = $.webPath() + "/kcgl/nbll/nbll_content";
    var actionUrl = $.webPath() + "/kcgl/nbll/nbll_llsq";
    nbll_showDialog(title, href, actionUrl);
}

//办理方法
function nbll_bl(title, action) {
    var record = $("#grid_nbll").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要办理的领料单!", "warning");
        return;
    }
    var href = $.webPath() + "/kcgl/nbll/nbll_blcontent?lldId=" + record.id;
    var actionUrl = $.webPath() + "/kcgl/nbll/" + action;
    nbllbl_showDialog(title, href, actionUrl);
}

//内部领料信息查看
//function nbll_detail(title) {
//    var record = $("#grid_nbll").datagrid("getSelected");
//    var href = $.webPath() + "/kcgl/nbll/nbll_detail?lldId=" + record.id;
//    nbll_showDetailDialog(title, href);
//}
////内部领料信息查看信息
//function nbll_showDetailDialog(title, href) {
//    var win = $.window({
//        title:title,
//        iconCls: 'icon-add2',
//        width:800,
//        height:450,
//        cache:false,
//        url:href,
//        modal:true
//    });
//}

//审核方法
function nbll_sh() {
    var row = $('#grid_nbll').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '是否对该领料单进行审核？', function (r) {
            if (r) {
                $.ajax({
                    url: $.webPath() + "/kcgl/nbll/nbll_sh",
                    dataType: 'json',
                    type: 'POST',
                    data: {lldId: row.id},
                    beforeSend: function () {
                        $("#layout_nbll").mask();
                    },
                    success: function (data) {
                        $("#layout_nbll").mask("hide");
                        if (data.statusCode == 200) {
                            $('#grid_nbll').datagrid('reload');
                            $.messager.show({
                                title: '提示',
                                msg: data.message,
                                timeout: 3000,
                                showType: 'slide'
                            });
                        } else {
                            $('#grid_nbll').datagrid('reload');
                            $.messager.alert("提示", data.message, "error");
                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选择要审核的领料单！", "warning");
    }
}

//弹框调用方法
function nbll_showDialog(title, href, actionUrl) {
    var win = $.window({
        title: title,
        iconCls: 'icon-add2',
        width: 1024,
        height: 500,
        cache: false,
        url: href,
        modal: true,
        buttons: [
            {
                text: '保存',
                handler: function () {
                    $('#lldForm').form('submit', {
                        url: actionUrl,
                        onSubmit: function (param) {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                return false;
                            }
                            var data = $('#lld_mx').edatagrid("getData");
                            if (!data.rows.length) {
                                $.messager.alert("提示", "请新增领料单明细!", "waring");
                                $('#lldForm').tabs('select', "领料信息");
                                return false;
                            }
                            $('#lld_mx').edatagrid('acceptChanges');
                            var arrayPrefix = 'lld.lldmxList';
                            var kcentiry = {};
                            //领料计划明细
                            var paramString = "{";
                            //领料计划明细
                            for (var i = 0; i < data.rows.length; i++) {
                                if (data.rows[i].kdsl == 0 || data.rows[i].kdsl == null) {
                                    $.messager.alert('提示', '第' + (i + 1) + '行的开单数量不能为0', 'info');
                                    return false;
                                }
                                var obj = data.rows[i];
                                if (obj['kh.id'] == undefined) {
                                    $('#lldForm').tabs('select', "领料明细");
                                    $.messager.alert("提示", "请选择卡号!", "waring");
                                    return false;
                                } else {
                                    if (kcentiry['s' + obj['kh.id']] != null) {
                                        var sl = parseFloat(kcentiry['s' + obj['kh.id']]) - parseFloat(obj['kdsl'].toString());
                                        if (sl >= 0)
                                            kcentiry['s' + obj['kh.id']] = sl;
                                        else {
                                            $('#lldForm').tabs('select', "领料明细");
                                            $.messager.alert("提示", "库存不够!", "waring");
                                            return false;
                                        }
                                    } else {
                                        kcentiry['s' + obj['kh.id']] = parseFloat(obj['kkdsl'].toString()) - obj['kdsl'];
                                    }
                                }
                                var objectString = $.toJSONStringSubPrefix(obj, arrayPrefix + "[" + i + "].", ['jzfs.id', 'jzfs.z', 'kdjs', 'kdsl', 'kddj', 'llbz', 'kh.id', 'flsl', 'fljs', 'fldj', "id"]);
                                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                            }
                            if (data.rows && data.rows.length > 0)
                                paramString = paramString.substring(0, paramString.length - 1);
                            paramString += "}";
                            $.extend(param, $.parseJSON(paramString));
                            return isValid;
                        },
                        success: function (data) {
                            var json = $.parseJSON(data);
                            if (json.statusCode == '200') {
                                $(win).window('close');
                                initNbll();
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

function nbllbl_showDialog(title, href, actionUrl) {
    var win = $.window({
        title: title,
        iconCls: 'icon-add2',
        width: 1024,
        height: 500,
        cache: false,
        url: href,
        modal: true,
        buttons: [
            {
                text: '保存',
                handler: function () {
                    $('#lldForm').form('submit', {
                        url: actionUrl,
                        onSubmit: function (param) {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                return false;
                            }
                            var data = $('#lld_mx').edatagrid("getData");
                            if (!data.rows.length) {
                                $.messager.alert("提示", "请新增领料单明细!", "waring");
                                $('#lldForm').tabs('select', "领料信息");
                                return false;
                            }
                            $('#lld_mx').edatagrid('acceptChanges');
                            var arrayPrefix = 'lld.lldmxList';
                            var kcentiry = {};
                            //领料计划明细
                            var paramString = "{";
                            //领料计划明细
                            for (var i = 0; i < data.rows.length; i++) {
                                if (data.rows[i].flsl == 0 || data.rows[i].flsl == null || data.rows[i].flsl > data.rows[i].kdsl) {
                                    $.messager.alert('提示', '第' + (i + 1) + '行的发料数量不能为0并且发料数量不能大于开单数量', 'info');
                                    return false;
                                }
                                var obj = data.rows[i];
                                if (obj['kh.id'] == undefined) {
                                    $('#lldForm').tabs('select', "领料明细");
                                    $.messager.alert("提示", "请选择卡号!", "waring");
                                    return false;
                                } else {
                                    if (kcentiry['s' + obj['kh.id']] != null) {
                                        var sl = parseFloat(kcentiry['s' + obj['kh.id']]) - parseFloat(obj['kdsl'].toString());
                                        if (sl >= 0)
                                            kcentiry['s' + obj['kh.id']] = sl;
                                        else {
                                            $('#lldForm').tabs('select', "领料明细");
                                            $.messager.alert("提示", "库存不够!", "waring");
                                            return false;
                                        }
                                    } else {
                                        kcentiry['s' + obj['kh.id']] = parseFloat(obj['kkdsl'].toString()) - obj['kdsl'];
                                    }
                                }
                                var objectString = $.toJSONStringSubPrefix(obj, arrayPrefix + "[" + i + "].", ['jzfs.id', 'jzfs.z', 'kdjs', 'kdsl', 'kddj', 'llbz', 'kh.id', 'flsl', 'fljs', "id"]);
                                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                            }
                            if (data.rows && data.rows.length > 0)
                                paramString = paramString.substring(0, paramString.length - 1);
                            paramString += "}";
                            $.extend(param, $.parseJSON(paramString));
                            return isValid;
                        },
                        success: function (data) {
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                initNbll();
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

//查询方法
function nbll_search() {
    var type = $("#toolbar_nbll input[name='nbll_zt']:checked").val();
    var kdrqStart = $('#nbll_kdrq_start').datebox('getValue');
    var kdrqEnd = $('#nbll_kdrq_end').datebox('getValue');
    var flgsId = $('#nbll_flgs').combotree('getValue') == null ? null : $('#nbll_flgs').combotree('getValue');
    var flgsJc = $('#nbll_flgs').combotree('getText') == null ? null : $('#nbll_flgs').combotree('getText');
    var options = $.extend(getBbllGridOption(type),
        {queryParams: {type: type, kdrqStart: kdrqStart, kdrqEnd: kdrqEnd, flgsId: flgsId, flgsJc: flgsJc}});
    $('#grid_nbll').datagrid(options);
}

//根据不同的type得到不同的表头
function getBbllGridOption(type) {
    var options = {
        url: $.webPath() + "/kcgl/nbll/nbllList?zt=" + type,
        toolbar: "#toolbar_nbll",
        fitColumns: true,
        singleSelect: true,
        pagination: true,
        fit: true,
        pageNumber: 1,
        rownumbers: true,
        onLoadSuccess: function () {
            $(this).datagrid('selectRow', 0);
            nbll.setBtnStatus();
            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onClickRow: function () {
            nbll.setBtnStatus();
        },
        onSelect: function (rowIndex, rowData) {
            if (rowData) {
                nbll.setBtnStatus();
            }
        }

    };
    if (type == "yfl") {
        var columns = {columns: [
            [
                {field: 'lldh', title: '领料单号', align: 'center', width: 50, formatter: nbllCell},
                {field: 'kdrq', title: '开单日期', align: 'center', width: 35},
                {field: 'flgs_jc', title: '发料公司', align: 'center', width: 45},
                {field: 'flbm_jc', title: '发料部门', align: 'center', width: 30},
                {field: 'thck_mc', title: '提货仓库', align: 'center', width: 35},
                {field: 'kdslzh', title: '开单数量', align: 'right', formatter: function (value) {
                    var sl = formatSl(value, ",");
                    return sl;
                }, width: 30},
                {field: 'kdjezh', title: '开单金额（不含税）', align: 'right', width: 50,
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }
                },
                {field: 'flslzh', title: '发料数量', align: 'right', formatter: function (value) {
                    var sl = formatSl(value, ",");
                    return sl;
                }, width: 30},
                {field: 'fljezh', title: '发料金额（不含税）', align: 'right', width: 50,
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }
                },
                {field: 'llgs_jc', title: '领料公司', align: 'center', width: 50},
                {field: 'llbm_jc', title: '领料部门', align: 'center', width: 30},
                {field: 'llr_xm', title: '领料人', align: 'center', width: 25},
                {field: 'flrq', title: '发料日期', align: 'center', width: 30},
                {field: 'flr_xm', title: '发料人', align: 'center', width: 25},
                {field: 'zt', title: '状态', width: 20, align: 'center',
                    formatter: function (value, row, index) {
                        if (value == 'ybc') {
                            return '已保存';
                        } else if (value == "ysp") {
                            return '已审批';
                        } else if (value == "yfl") {
                            return '已发料';
                        }
                    }}
            ]
        ]}
        options = $.extend(options, columns);
    } else {
        var columns = {columns: [
            [
                {field: 'lldh', title: '领料单号', align: 'center', width: 50, formatter: nbllCell},
                {field: 'kdrq', title: '开单日期', align: 'center', width: 35},
                {field: 'flgs_jc', title: '发料公司', align: 'center', width: 45},
                {field: 'flbm_jc', title: '发料部门', align: 'center', width: 30},
                {field: 'thck_mc', title: '提货仓库', align: 'center', width: 35},
                {field: 'kdslzh', title: '开单数量', align: 'right', formatter: function (value) {
                    var sl = formatSl(value, ",");
                    return sl;
                }, width: 30},
                {field: 'kdjezh', title: '开单金额（不含税）', align: 'right', width: 50,
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }
                },
                {field: 'llgs_jc', title: '领料公司', align: 'center', width: 50},
                {field: 'llbm_jc', title: '领料部门', align: 'center', width: 30},
                {field: 'llr_xm', title: '领料人', align: 'center', width: 25},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: function (value, row, index) {
                    if (value == 'ybc') {
                        return '已保存';
                    } else if (value == "ysp") {
                        return '已审批';
                    } else if (value == "yfl") {
                        return '已发料';
                    }
                }}
            ]
        ]}
        options = $.extend(options, columns);
    }
    return options;
}

//初始化加载内部领料页面
function initNbll() {
    var type = $("#toolbar_nbll input[name='nbll_zt']:checked").val();
    var options = getBbllGridOption(type);
    $('#grid_nbll').datagrid(options);
}